﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MinistryStandardPlatformEntity;
using MinistryStandardPlatformWeb;
using Webdiyer.WebControls.Mvc;

namespace MinistryStandardPlatformWeb.Controllers
{
    [IsLogin]
    public class ContractController : Controller
    {
        //
        // GET: /Contract/
        private MSPDataContext context = new MSPDataContext();

        [MenuAuthorized("15")]
        public ActionResult Index()
        {
            var contracts = from c in context.InfoContract
                            orderby c.FinsertTime descending
                          select c;

            if (!string.IsNullOrEmpty(Request.QueryString["id"]))
            {
                string id = HttpUtility.UrlDecode(Request.QueryString["id"]);
                contracts = from c in contracts
                            where c.ParentUnitId == id
                            orderby c.FinsertTime descending
                            select c;

            }
            return PartialView(contracts.ToPagedList(1, CommonDictionary.PageSize));
        }

        [MenuAuthorized("154")]
        public ActionResult Data(string condition, string unitId, string searchAll, int pageIndex = 1)
        {
            var contracts = from c in context.InfoContract
                         orderby c.FinsertTime descending
                         select c;
            if (!string.IsNullOrEmpty(unitId) && searchAll != "on")
            {
                contracts = from c in contracts
                         where c.ParentUnitId == unitId
                         orderby c.FinsertTime descending
                         select c;
            }
            if (!string.IsNullOrEmpty(unitId) && searchAll == "on")
            {
                List<string> ids = CommonFunctions.GetAllChildrenUnits(unitId, CommonFunctions.GetLoginUser().UserId);
                ids.Add(unitId);
                contracts = from r in contracts
                          where ids.Contains(r.ParentUnitId)
                          orderby r.ParentUnitId,r.FinsertTime descending
                          select r;
            }
            if (!string.IsNullOrEmpty(condition))
            {
                contracts = from c in contracts
                         where c.ContractName.Contains(condition)
                            orderby c.FinsertTime descending
                         select c;
            }
            return PartialView(contracts.ToPagedList(pageIndex, CommonDictionary.PageSize));
        }


        [MenuAuthorized("151")]
        public ActionResult Create()
        {
            //ViewBag.clients=context.InfoClient
            string unitId = HttpUtility.UrlDecode(Request.QueryString["unitId"]);
            string unitName = HttpUtility.UrlDecode(Request.QueryString["unitName"]);
            return View(new InfoContract()
                {
                    ParentUnitId = unitId,
                    InfoUnit = new InfoUnit()
                    {
                        UNITID = unitId,
                        UNITNAME = unitName
                    }
                });
        }

        public ActionResult PickParentUnit()
        {
            var units = context.RightsDetails.Where(u => u.UserId == CommonFunctions.GetLoginUser().UserId && u.NodeTYPE == true).Select(u => new { NodeId = u.NodeId, ParentNodeId = u.ParentNodeId, NodeName = u.NodeName });
            List<ZTreeNode> nodes = new List<ZTreeNode>();
            foreach (var unit in units)
            {
                ZTreeNode node = new ZTreeNode();
                node.id = unit.NodeId;
                node.pId = unit.ParentNodeId;
                node.name = unit.NodeName;
                node.icon = "/Content/themes/zTreeStyle/img/diy/1_open.png";
                if (unit.ParentNodeId == null)
                {
                    node.open = true;
                }
                else
                {
                    node.open = false;
                }
                nodes.Add(node);
            }
            ViewBag.nodesJson = CommonFunctions.ListToJsonStr<ZTreeNode>(nodes);
            return View();
        }

        public ActionResult PickClient()
        {
            string unitId = HttpUtility.UrlDecode(Request.QueryString["unitId"]);
            var clients = context.InfoClient.Where(c => c.ParentUnitId == unitId).Select(u => new { NodeId = u.ClientID,ParentNodeId="", NodeName = u.ClientName });
            List<ZTreeNode> nodes = new List<ZTreeNode>();
            foreach (var client in clients)
            {
                ZTreeNode node = new ZTreeNode();
                node.id = client.NodeId;
                node.pId = client.ParentNodeId;
                node.name = client.NodeName;
                node.icon = "/Content/themes/zTreeStyle/img/diy/1_open.png";
                node.open = true;
                nodes.Add(node);
            }

            ZTreeNode node1 = new ZTreeNode();
            node1.id = null;
            node1.pId = "";
            node1.name = "清空";
            node1.icon = "/Content/themes/zTreeStyle/img/diy/1_open.png";
            node1.open = true;
            nodes.Add(node1);

            ViewBag.nodesJson = CommonFunctions.ListToJsonStr<ZTreeNode>(nodes);
            return View();
        }

        [HttpPost]
        [MenuAuthorized("151")]
        public ActionResult Create(InfoContract contract)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    contract.FinsertTime = DateTime.Now;
                    contract.ContractId = "CONT" + CommonFunctions.GetDateTimeStrAnd4BitsRandom();
                    contract.Inuserid = CommonFunctions.GetLoginUser().UserId;
                    context.InfoContract.InsertOnSubmit(contract);
                    context.SubmitChanges();
                    ViewBag.Message = "添加成功";
                }
                catch (System.Exception ex)
                {
                    ViewBag.Message = "添加失败," + ex.Message;
                }
            }
            else
            {
                ViewBag.Message = "添加失败";
            }

            return View(contract);
        }

        [MenuAuthorized("152")]
        public ActionResult Delete(string parameters)
        {
            var contract = context.InfoContract.SingleOrDefault(c => c.ContractId == parameters);
            try
            {
                context.InfoContract.DeleteOnSubmit(contract);
                context.SubmitChanges();
                return Json(new { success = true, message = "" });
            }
            catch (System.Exception ex)
            {
                return Json(new { success = false, message = ex.Message });
            }
        }

        [MenuAuthorized("153")]
        public ActionResult Edit(string id)
        {
            var contract = context.InfoContract.SingleOrDefault(c => c.ContractId == id);
            return View(contract);
        }

        [HttpPost]
        [MenuAuthorized("153")]
        public ActionResult Edit(FormCollection form)
        {
            try
            {
                var contractToUpdate = context.InfoContract.SingleOrDefault(c => c.ContractId == form["ContractId"]);
                UpdateModel(contractToUpdate, form.ToValueProvider());
                context.SubmitChanges();
                ViewBag.Message = "修改成功";

                return View(contractToUpdate);
            }
            catch (System.Exception ex)
            {
                ViewBag.Message = "修改失败," + ex.Message;
                return View(new InfoContract());
            }
        }

    }
}
